package com.daisuxia.back.controller;

import java.io.OutputStream;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.daisuxia.back.service.IBackUserService;
import com.daisuxia.back.service.IRiskUserService;
import com.daisuxia.back.service.ITaskJob;
import com.daisuxia.back.utils.DwzResult;
import com.daisuxia.back.utils.ExcelUtil;
import com.daisuxia.back.utils.SpringUtils;
import com.daisuxia.constant.Constant;
import com.daisuxia.risk.pojo.RiskCreditUser;
import com.daisuxia.risk.pojo.RiskRuleCal;
import com.daisuxia.ts.service.ITsOrdersService;
import com.daisuxia.web.controller.BaseController;
import com.daisuxia.web.pojo.BackLog;
import com.daisuxia.web.pojo.BackUser;
import com.daisuxia.web.pojo.BorrowOrder;
import com.daisuxia.web.pojo.BorrowOrderChecking;
import com.daisuxia.web.pojo.BorrowOrderCheckingExt;
import com.daisuxia.web.pojo.BorrowOrderLoan;
import com.daisuxia.web.pojo.BorrowOrderLoanPerson;
import com.daisuxia.web.pojo.Repayment;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.pojo.UserCardInfo;
import com.daisuxia.web.pojo.UserInfoImage;
import com.daisuxia.web.pojo.UserLimitRecord;
import com.daisuxia.web.service.IBorrowOrderService;
import com.daisuxia.web.service.IJsStepRecordService;
import com.daisuxia.web.service.IRepaymentService;
import com.daisuxia.web.service.IUserInfoImageService;
import com.daisuxia.web.service.IUserService;
import com.daisuxia.web.util.DateUtil;
import com.daisuxia.web.util.GenerateNo;
import com.daisuxia.web.util.PageConfig;
import com.daisuxia.web.util.SendSmsUtil;
import com.daisuxia.web.util.ThreadPool3;

import redis.clients.jedis.JedisCluster;

@Controller
@RequestMapping("backBorrowOrder/")
public class BorrowOrderController extends BaseController {

	private static Logger logger = LoggerFactory.getLogger(BorrowOrderController.class);

	@Autowired
	private IBorrowOrderService borrowOrderService;
	@Autowired
	private IRepaymentService repaymentService;
	@Autowired
	public IUserService userService;
	@Autowired
	private IUserInfoImageService userInfoImageService;
	@Autowired
	private ITaskJob taskJob;
	@Autowired
	@Qualifier("riskUserService")
	private IRiskUserService riskUserService;
	@Autowired
	private IBackUserService backUserService;
	@Autowired
	JedisCluster jedisCluster;
	@Autowired
	private ITsOrdersService tsOrdersService;
	@Autowired
	private IJsStepRecordService jsStepRecordService;

	@RequestMapping("addUserLimit")
	public void addUserLimit(HttpServletRequest request, HttpServletResponse response, Model model) {

		User user = userService.searchByUserid(Integer.parseInt(request.getParameter("userId")));
		borrowOrderService.addUserLimit(user);
	}
	/**
	 * 借款申请列表-用户借款管理-借款管理--asset-borrow-order
	 * 放款审核列表-用户借款管理-借款管理--asset-borrow-order
	 * 机审订单--风控管理--asset-borrow-order
	 * 人工复审--风控管理--asset-borrow-order
	 * 
	 */
	@RequestMapping("getBorrowPage")
	public String getUserPage(HttpServletRequest request, HttpServletResponse response, Model model) {
		
		String url = "borrow/borrowList";
		try {

			HashMap<String, Object> params = getParametersO(request);

			if (params.containsKey("bType")) {
				if (params.get("bType").equals("fangk")) {// 放款界面看到的状态

					params.put("statusList", Arrays.asList(BorrowOrder.STATUS_FSTG, BorrowOrder.STATUS_HKZ, BorrowOrder.STATUS_FKZ,
							BorrowOrder.STATUS_FKBH, BorrowOrder.STATUS_FKSB));
					url = "borrow/borrowList_fk";
				} else if (params.get("bType").toString().contains("fengk")) {// 风控界面看到的状态

					if (params.get("bType").equals("fengk_Trial")) {// 初审
						params.put("statusList", Arrays.asList(BorrowOrder.STATUS_CSTG, BorrowOrder.STATUS_DCS, BorrowOrder.STATUS_CSBH
						// ,
						// BorrowOrder.STATUS_JSJJ
								));
					} else if (params.get("bType").equals("fengk_Review")) {// 复审

						params.put("statusList", Arrays.asList(BorrowOrder.STATUS_CSTG, BorrowOrder.STATUS_FSBH, BorrowOrder.STATUS_FSTG));
					} else {

						params.put("statusList", Arrays.asList(BorrowOrder.STATUS_CSTG, BorrowOrder.STATUS_FSTG, BorrowOrder.STATUS_FSBH,
						// BorrowOrder.STATUS_JSJJ,
								BorrowOrder.STATUS_DCS));
					}

					// url = "borrow/fk_borrowList";
				}

				model.addAttribute("bType", params.get("bType"));
			}

			PageConfig<BorrowOrder> pageConfig = borrowOrderService.findPage(params);
			model.addAttribute("pm", pageConfig);
			// model.addAttribute("borrowStatusMap",
			// BorrowOrder.borrowStatusMap);
			model.addAttribute("params", params);// 用于搜索框保留值

		} catch (Exception e) {
			logger.error("getUserPage error", e);
		}
		return url;
	}
	/**
	 * 对账功能-用户借款管理-借款管理--asset-borrow-order
	 * 
	 */
	@RequestMapping("getBorrowPageByStatus/{borrowStatus}")
	public String getBorrowPageByParams(HttpServletRequest request, HttpServletResponse response, @PathVariable("borrowStatus") String borrowStatus,
			Model model) {

		// System.out.println(borrowStatus);
		String url = "borrow/borrowList";
		try {

			HashMap<String, Object> params = getParametersO(request);
			params.put("borrowStatusArray", borrowStatus);// 格式1,1,3.5
			if (params.containsKey("bType")) {
				if (params.get("bType").equals("fangk")) {// 放款界面看到的状态

					// params.put("statusList",
					// Arrays.asList(BorrowOrder.STATUS_FSTG,
					// BorrowOrder.STATUS_HKZ, BorrowOrder.STATUS_FKZ,
					// BorrowOrder.STATUS_FKBH, BorrowOrder.STATUS_FKSB));
					url = "borrow/borrowList_fk";
				} else if (params.get("bType").toString().contains("fengk")) {// 风控界面看到的状态

					if (params.get("bType").equals("fengk_Trial")) {// 初审
						// params.put("statusList",
						// Arrays.asList(BorrowOrder.STATUS_CSTG,
						// BorrowOrder.STATUS_DCS, BorrowOrder.STATUS_CSBH
						//
						// ));
					} else if (params.get("bType").equals("fengk_Review")) {// 复审

						// params.put("statusList",
						// Arrays.asList(BorrowOrder.STATUS_CSTG,
						// BorrowOrder.STATUS_FSBH, BorrowOrder.STATUS_FSTG));
					} else {

						// params.put("statusList",
						// Arrays.asList(BorrowOrder.STATUS_CSTG,
						// BorrowOrder.STATUS_FSTG, BorrowOrder.STATUS_FSBH,
						// // BorrowOrder.STATUS_JSJJ,
						// BorrowOrder.STATUS_DCS));
					}

					// url = "borrow/fk_borrowList";
				} else if (params.get("bType").equals("duizhang")) {// 放款界面看到的状态

					Long moneyAmountSum = borrowOrderService.findMoneyAmountSucSum(params);
					Long intoMoneySum = borrowOrderService.findIntoMoneySucSum(params);
					model.addAttribute("moneyAmountSum", moneyAmountSum);
					model.addAttribute("intoMoneySum", intoMoneySum);
					// params.put("statusList",
					// Arrays.asList(BorrowOrder.STATUS_FSTG,
					// BorrowOrder.STATUS_HKZ, BorrowOrder.STATUS_FKZ,
					// BorrowOrder.STATUS_FKBH, BorrowOrder.STATUS_FKSB));
					url = "borrow/borrowList_dz";
				}
				model.addAttribute("bType", params.get("bType"));
			}

			PageConfig<BorrowOrder> pageConfig = borrowOrderService.findPage(params);
			model.addAttribute("pm", pageConfig);
			// model.addAttribute("borrowStatusMap",
			// BorrowOrder.borrowStatusMap);
			model.addAttribute("params", params);// 用于搜索框保留值

		} catch (Exception e) {
			logger.error("getUserPage error", e);
		}
		return url;
	}

	@RequestMapping("getBorrowDetailById")
	public String getBorrowDetailById(HttpServletRequest request, HttpServletResponse response, Model model) {

		HashMap<String, Object> params = this.getParametersO(request);
		Integer id = Integer.valueOf(String.valueOf(params.get("id")));
		BorrowOrder borrow = borrowOrderService.findOneBorrow(id);
		model.addAttribute("borrow", borrow);

		HashMap<String, Object> paramsM = new HashMap<String, Object>();

		paramsM.put("userId", borrow.getUserId());

		List<BorrowOrder> userBorrows = borrowOrderService.findAll(paramsM);
		model.addAttribute("userBorrows", userBorrows);
		User user = userService.searchByUserid(borrow.getUserId());
		String cardNo = user.getIdNumber();
		if (cardNo != null && cardNo.length() >= 18) {
			String yy = cardNo.substring(6, 10); // 出生的年份
			String mm = cardNo.substring(10, 12); // 出生的月份
			String dd = cardNo.substring(12, 14); // 出生的日期
			String birthday = yy.concat("-").concat(mm).concat("-").concat(dd);
			model.addAttribute("birthday", birthday);
			model.addAttribute("age", SpringUtils.calculateAge(birthday, "yyyy-MM-dd"));
		}
		user.setEducation(User.EDUCATION_TYPE.get(user.getEducation()));
		user.setPresentPeriod(User.RESIDENCE_DATE.get(user.getPresentPeriod()));
		user.setMaritalStatus(User.MARRIAGE_STATUS.get(user.getMaritalStatus()));
		user.setFristContactRelation(User.CONTACTS_FAMILY.get(user.getFristContactRelation()));
		user.setSecondContactRelation(User.CONTACTS_OTHER.get(user.getSecondContactRelation()));
		model.addAttribute("user", user);

		UserCardInfo info = userService.findUserBankCard(borrow.getUserId());
		model.addAttribute("bankCard", info);
		List<UserInfoImage> userInfoImage = this.userInfoImageService.selectImageByUserId(borrow.getUserId());
		model.addAttribute("InfoImage", userInfoImage);
		model.addAttribute("params", params);

		// 查询征信信息
		RiskCreditUser riskCreditUser = riskUserService.findRiskCreditUserByAssetsId(String.valueOf(id));
		if (null != riskCreditUser) {
			model.addAttribute("riskCreditUser", riskCreditUser);
		}

		// 规则查询
		List<RiskRuleCal> riskRuleCalList = riskUserService.findRiskRuleCalByAssetsId(String.valueOf(id));
		model.addAttribute("riskRuleCalList", riskRuleCalList);

		return "borrow/borrowdetail";
	}

	/**
	 * 放款审核（按钮）--放款审核列表--用户借款管理--借款管理
	 * 审核（按钮）...
	 * @param request
	 * @param response
	 * @param model
	 * @param borrowOrder
	 * @return
	 */
	@RequestMapping("saveUpdateBorrow")
	public String saveUpdateBorrow(HttpServletRequest request, HttpServletResponse response, Model model, BorrowOrder borrowOrder) {

		HashMap<String, Object> params = this.getParametersO(request);
		String url = null;
		String erroMsg = null;
		try {

			if ("toJsp".equals(String.valueOf(params.get("type")))) {

				Integer id = Integer.valueOf(String.valueOf(params.get("id")));

				// model.addAttribute("borrow",
				// borrowOrderService.findOneBorrow(id));

				BorrowOrder borrow = borrowOrderService.findOneBorrow(id);
				model.addAttribute("borrow", borrow);

				HashMap<String, Object> paramsM = new HashMap<String, Object>();

				paramsM.put("userId", borrow.getUserId());

				List<BorrowOrder> userBorrows = borrowOrderService.findAll(paramsM);
				model.addAttribute("userBorrows", userBorrows);
				User user = userService.searchByUserid(borrow.getUserId());
				String cardNo = user.getIdNumber();
				if (cardNo != null && cardNo.length() >= 18) {
					String yy = cardNo.substring(6, 10); // 出生的年份
					String mm = cardNo.substring(10, 12); // 出生的月份
					String dd = cardNo.substring(12, 14); // 出生的日期
					String birthday = yy.concat("-").concat(mm).concat("-").concat(dd);
					model.addAttribute("birthday", birthday);
					model.addAttribute("age", SpringUtils.calculateAge(birthday, "yyyy-MM-dd"));
				}
				user.setEducation(User.EDUCATION_TYPE.get(user.getEducation()));
				user.setPresentPeriod(User.RESIDENCE_DATE.get(user.getPresentPeriod()));
				user.setMaritalStatus(User.MARRIAGE_STATUS.get(user.getMaritalStatus()));
				user.setFristContactRelation(User.CONTACTS_FAMILY.get(user.getFristContactRelation()));
				user.setSecondContactRelation(User.CONTACTS_OTHER.get(user.getSecondContactRelation()));
				model.addAttribute("user", user);

				UserCardInfo info = userService.findUserBankCard(borrow.getUserId());
				model.addAttribute("bankCard", info);
				List<UserInfoImage> userInfoImage = this.userInfoImageService.selectImageByUserId(borrow.getUserId());
				model.addAttribute("InfoImage", userInfoImage);

				model.addAttribute("params", params);

				// 查询征信信息
				RiskCreditUser riskCreditUser = riskUserService.findRiskCreditUserByAssetsId(String.valueOf(id));
				if (null != riskCreditUser) {
					model.addAttribute("riskCreditUser", riskCreditUser);
				}

				// 规则查询
				List<RiskRuleCal> riskRuleCalList = riskUserService.findRiskRuleCalByAssetsId(String.valueOf(id));
				model.addAttribute("riskRuleCalList", riskRuleCalList);

				url = "borrow/borrow_check";
				if (params.containsKey("bType")) {
					if (params.get("bType").equals("fangk")) {// 放款界面看到的状态
						url = "borrow/borrow_fangk_check";
					} else if (params.get("bType").toString().contains("fengk")) {// 风控界面看到的状态

						if (params.get("bType").equals("fengk_Trial")) {// 初审
							url = "borrow/borrow_trial_check";
						} else if (params.get("bType").equals("fengk_Review")) {// 复审
							url = "borrow/borrow_review_check";
						}
						// url = "borrow/fk_borrowList";
					}
					model.addAttribute("bType", params.get("bType"));
				}

			} else {
				// // 更新或者添加操作
				if (borrowOrder.getId() != null) {
					String key = BorrowOrder.REVIEW_BORROW + borrowOrder.getId();
					String value = key;

					if (jedisCluster.get(key) != null) {
						SpringUtils.renderDwzResult(response, false, "操作失败,原因：该订单正在被审核，请稍后操作！", DwzResult.CALLBACK_CLOSECURRENT,
								params.get("parentId").toString());
					} else {

						jedisCluster.setex(BorrowOrder.REVIEW_BORROW + borrowOrder.getId(), BorrowOrder.REVIEW_BORROW_SECOND, value);
						// Thread.sleep(10000);
						Date nowDate = new Date();
						BorrowOrder borrowOrderR = borrowOrderService.findOneBorrow(borrowOrder.getId());
						Date  updateTime=borrowOrderR.getUpdatedAt();
						if ((BorrowOrder.borrowStatusMap_shenheFail.containsKey(borrowOrderR.getStatus()) && borrowOrderR.getStatus() != BorrowOrder.STATUS_CSBH)
								|| BorrowOrder.STATUS_HKZ == borrowOrderR.getStatus()// 放款成功的不让再审核
						) {// 审核失败的不让再继续审核了,除了初审驳回
							SpringUtils.renderDwzResult(response, false, "当前状态为:<b>" + borrowOrderR.getStatusName() + "</b>,该借款状态不支持继续审核！",
									DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId").toString());
						}else {

							BackUser backUser = loginAdminUser(request);
							borrowOrder.setUpdatedAt(nowDate);
							if (params.get("bType").equals("fengk_Trial")) {// 初审
								borrowOrder.setVerifyTrialTime(nowDate);
								borrowOrder.setVerifyTrialRemark(borrowOrder.getRemark());
								borrowOrder.setVerifyTrialUser(backUser.getUserAccount());
							} else if (params.get("bType").equals("fengk_Review")) {// 复审
								borrowOrder.setVerifyReviewTime(nowDate);
								borrowOrder.setVerifyReviewRemark(borrowOrder.getRemark());
								borrowOrder.setVerifyReviewUser(backUser.getUserAccount());
							} else if (params.get("bType").equals("fangk")) {// 放款审核
								
								backUserService.insertLog(new BackLog(loginAdminUser(request).getId(), "fangkVerifyLoan", borrowOrderR.getId()
										.toString()));

								borrowOrder.setVerifyLoanTime(new Date());
								borrowOrder.setVerifyLoanRemark(borrowOrder.getRemark());
								borrowOrder.setVerifyLoanUser(backUser.getUserAccount());

							}

							// 重新放款
							if (borrowOrder.getStatus().intValue() == Integer.parseInt(BorrowOrder.STATUS_FKZ + "2")) {
								boolean checkIsApproved =DateUtil.checkIsApproved(nowDate, updateTime);
								
								if(checkIsApproved){
									SpringUtils.renderDwzResult(response, false, "该借款半小时内不支持重复审核！",
											DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId").toString());
									model.addAttribute("params", params);
									return url;
								}
								backUserService.insertLog(new BackLog(loginAdminUser(request).getId(), "againToBatchSign", borrowOrderR.getId()
										.toString()));
								List<Repayment> lists = repaymentService.findAllByBorrowId(borrowOrderR.getId());
								if (lists == null || lists.size() < 1) {
									if (borrowOrderR.getStatus().intValue() != BorrowOrder.STATUS_HKZ
											&& !borrowOrderR.getPaystatus().equals(BorrowOrder.SUB_PAY_CSZT)
											&& (borrowOrderR.getStatus().intValue() == BorrowOrder.STATUS_FKZ || borrowOrderR.getStatus().intValue() == BorrowOrder.STATUS_FKSB)) {
										borrowOrder.setYurref(GenerateNo.payRecordNo("A"));
										borrowOrder.setSerialNo(GenerateNo.generateShortUuid(10));
										borrowOrder.setPaystatus(BorrowOrder.SUB_PAY_CSZT);
										borrowOrder.setStatus(BorrowOrder.STATUS_FKZ);
										borrowOrder.setRemark("重新放款：" + borrowOrder.getRemark() + ";上次招行订单号：" + borrowOrderR.getYurref());
										borrowOrder.setVerifyLoanTime(new Date());
										borrowOrder.setVerifyLoanRemark("重新放款：" + borrowOrder.getRemark() + borrowOrder.getVerifyLoanRemark());

									} else {
										SpringUtils.renderDwzResult(response, false, "操作失败,原因：该订单不能被进行重新放款操作，如有疑问请联系技术人员！",
												DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId").toString());
										model.addAttribute("params", params);
										return url;
									}
								} else {
									SpringUtils.renderDwzResult(response, false, "操作失败,原因：该订单不能被进行重新放款操作，如有疑问请联系技术人员！",
											DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId").toString());
									model.addAttribute("params", params);
									return url;
								}
							}   
							borrowOrderService.updateById(borrowOrder);
							try {
								tsOrdersService.sendBorrowStatus(borrowOrder.getId());
							} catch (Exception e) {
								logger.error("sendBorrowStatus:",e);
							}
							if (borrowOrderR.getStatus() == BorrowOrder.STATUS_DCS) {
								RiskCreditUser riskCreditUser = new RiskCreditUser();
								riskCreditUser.setAssetId(borrowOrderR.getId());
								riskCreditUser.setRiskStatus(6);
								borrowOrderService.updateRiskCreditUserById(riskCreditUser);
							} else if (borrowOrderR.getStatus() == BorrowOrder.STATUS_CSBH) {// 初审驳回后被救回
								RiskCreditUser riskCreditUser = new RiskCreditUser();
								riskCreditUser.setAssetId(borrowOrderR.getId());
								riskCreditUser.setRiskStatus(7);
								borrowOrderService.updateRiskCreditUserById(riskCreditUser);

								// 初审驳回后被救回需要冻结借款金额
								User user = userService.searchByUserid(borrowOrderR.getUserId());
								User newUser = new User();
								newUser.setId(user.getId());
								newUser.setAmountAvailable(String.valueOf(Integer.valueOf(user.getAmountAvailable()) - borrowOrderR.getMoneyAmount()));

								// if(Integer.parseInt(newUser.getAmountAvailable())>Integer.parseInt(user.getAmountMax())){
								// logger.error("退回额度出错！可用额度大于最大额度。将可用额度重置为最大额度！");
								// newUser.setAmountAvailable(user.getAmountAvailable());
								// }
								newUser.setUpdateTime(nowDate);
								userService.updateByPrimaryKeyUser(newUser);
								logger.info("kou UserLimit sucess 初审驳回后被救回扣除用户可用额度！");

							}
							/**
							 * 2017-02-20 zjb
							 */
							if (borrowOrder.getStatus() == BorrowOrder.STATUS_FSTG || borrowOrder.getStatus() == BorrowOrder.STATUS_FSBH
									|| borrowOrder.getStatus() == BorrowOrder.STATUS_FKBH|| borrowOrder.getStatus() == BorrowOrder.STATUS_FKZ) {
								logger.error("update riskUser because:"+borrowOrder.getStatus());
								RiskCreditUser riskCreditUser = new RiskCreditUser();
								riskCreditUser.setAssetId(borrowOrderR.getId());
								if (borrowOrder.getStatus() == BorrowOrder.STATUS_FSTG) {
									riskCreditUser.setRiskStatus(10);
								} else if (borrowOrder.getStatus() == BorrowOrder.STATUS_FSBH) {
									riskCreditUser.setRiskStatus(11);
								} else if (borrowOrder.getStatus() == BorrowOrder.STATUS_FKBH) {
									riskCreditUser.setRiskStatus(12);
								} else if (borrowOrder.getStatus() == BorrowOrder.STATUS_FKZ) {
									riskCreditUser.setRiskStatus(13);
								}

								borrowOrderService.updateRiskCreditUserById(riskCreditUser);
							}

							// 审核失败，退回可用额度
							if (BorrowOrder.borrowStatusMap_shenheFail.containsKey(borrowOrder.getStatus())) {
								
								final Integer userId = borrowOrder.getUserId();
								final String orderNo2 = borrowOrder.getOutTradeNo();
								final Integer status = borrowOrder.getStatus();
								ThreadPool3.getInstance().run(new Runnable() {
									@Override
									public void run() {
										HashMap<String, Object> params = new HashMap<String, Object>();
										params.put("userId", userId);
										params.put("orderNo", orderNo2);
										params.put("status", status);
										params.put("soketOut", "5000");
										params.put("connOut", "5000");
										tsOrdersService.updateSy(params);
									}
								});
								User user = userService.searchByUserid(borrowOrderR.getUserId());
								User newUser = new User();
								newUser.setId(user.getId());
								newUser.setAmountAvailable(String.valueOf(Integer.valueOf(user.getAmountAvailable()) + borrowOrderR.getMoneyAmount()));
								newUser.setUpdateTime(nowDate);
								userService.updateByPrimaryKeyUser(newUser);
								logger.info("return UserLimit sucess 审核不通过恢复用户可用额度！");
							}

							// 测试放款成功 xxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
							if (borrowOrder.getStatus().intValue() == BorrowOrder.STATUS_HKZ) {

								Date fkDate = new Date();
//								borrowOrderR.setPaystatus(BorrowOrder.SUB_PAY_CSZT);
								borrowOrderR.setLoanTime(fkDate);
								borrowOrderR.setRemark("手动放款成功");
								borrowOrderR.setPaystatus(BorrowOrder.SUB_PAY_SUCC);
								borrowOrderR.setPayRemark("手动放款成功");
								borrowOrderR.setStatus(BorrowOrder.STATUS_HKZ);
								borrowOrderR.setLoanEndTime(DateUtil.addDay(fkDate, borrowOrderR.getLoanTerm()));// 放款时间加上借款期限
								repaymentService.insertByBorrorOrder(borrowOrderR);
 								borrowOrderService.addBorrowChecking(borrowOrderR);
//								borrowOrderService.addBorrowCheckingExt(borrowOrderR);
							}
							jedisCluster.del(key);
							// risk_credit_user

							SpringUtils.renderDwzResult(response, true, "操作成功", DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId").toString());

						}
					}

				} else {
					// 增加
				}

			}

		} catch (Exception e) {
			if (url == null) {

				SpringUtils
						.renderDwzResult(response, false, "操作失败,原因：" + erroMsg, DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId").toString());
			}
			logger.error("添加权限信息失败，异常信息:", e);
		}
		model.addAttribute(MESSAGE, erroMsg);
		model.addAttribute("params", params);
		return url;

	}

	/**
	 * 跳过机审，初审通过
	 * 跳过机审(按钮)--借款申请列表--用户借款管理--借款管理
	 * @param request
	 * @param response
	 * @param model
	 * @param borrowOrder
	 * @return
	 */
	@RequestMapping("saveUpdateBorrowTGJS")
	public String saveUpdateBorrowTGJS(HttpServletRequest request, HttpServletResponse response, Model model, BorrowOrder borrowOrder) {

		HashMap<String, Object> params = this.getParametersO(request);
		String url = null;
		String erroMsg = null;
		try {

			// // 更新或者添加操作
			if (borrowOrder.getId() != null) {
				String key = BorrowOrder.REVIEW_BORROW + borrowOrder.getId();
				String value = key;

				if (jedisCluster.get(key) != null) {
					SpringUtils.renderDwzResult(response, false, "操作失败,原因：该订单正在被审核，请稍后操作！", DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId")
							.toString());
				} else {

					jedisCluster.setex(BorrowOrder.REVIEW_BORROW + borrowOrder.getId(), BorrowOrder.REVIEW_BORROW_SECOND, value);
					BorrowOrder borrowOrderR = borrowOrderService.findOneBorrow(borrowOrder.getId());
					// 待机审核、机审失败的才可以
					if (borrowOrderR.getStatus().intValue() == BorrowOrder.STATUS_DCS
					//
					// || borrowOrderR.getStatus().intValue() ==
					// BorrowOrder.STATUS_JSJJ
					) {
						BackUser backUser = loginAdminUser(request);

						borrowOrder.setUpdatedAt(new Date());

						borrowOrder.setStatus(BorrowOrder.STATUS_CSTG);
						borrowOrder.setRemark("人工操作跳过机审！");

						borrowOrder.setVerifyTrialTime(new Date());
						borrowOrder.setVerifyTrialRemark(borrowOrder.getRemark());
						borrowOrder.setVerifyTrialUser(backUser.getUserName());

						borrowOrderService.updateById(borrowOrder);
						//发送订单状态给第三方渠道
						tsOrdersService.sendBorrowStatus(borrowOrder.getId());

						if (borrowOrderR.getStatus() == BorrowOrder.STATUS_DCS) {
							RiskCreditUser riskCreditUser = new RiskCreditUser();
							riskCreditUser.setAssetId(borrowOrderR.getId());
							riskCreditUser.setRiskStatus(6);//更改风控状态为已人工审核
							borrowOrderService.updateRiskCreditUserById(riskCreditUser);
						}

						SpringUtils.renderDwzResult(response, true, "操作成功", DwzResult.CALLBACK_CLOSECURRENTDIALOG, params.get("parentId").toString());

					} else {

						SpringUtils.renderDwzResult(response, false, "操作失败,原因：该状态不能跳过机审或者已经过了机审！", DwzResult.CALLBACK_CLOSECURRENTDIALOG,
								params.get("parentId").toString());

					}
				}
			}

		} catch (Exception e) {
			if (url == null) {

				SpringUtils.renderDwzResult(response, false, "操作失败,原因：" + erroMsg, DwzResult.CALLBACK_CLOSECURRENTDIALOG, params.get("parentId")
						.toString());
			}
			logger.error("跳过机审失败，异常信息:", e);
		}
		model.addAttribute(MESSAGE, erroMsg);
		model.addAttribute("params", params);
		return url;

	}

	/**
	 * 放款回调
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @param borrowOrder
	 * @return
	 */
	@RequestMapping("creditReCallBack")
	public void creditReCallBack(HttpServletRequest request, HttpServletResponse response, Model model) {

/*		// HashMap<String, Object> params = this.getParametersO(request);

		String borrowId = request.getParameter("bId");// 借款id，或者是其它唯一标识

		String isSuccess = request.getParameter("code");// 0000成功，其它失败。例如
		try {
			BorrowOrder borrowOrderR = borrowOrderService.findOneBorrow(Integer.parseInt(borrowId));
			// // 更新或者添加操作
			if (borrowOrderR != null) {

				if (borrowOrderR.getStatus().intValue() != BorrowOrder.STATUS_HKZ.intValue()) {// 放款成功
					Date fkDate = new Date();

					if (isSuccess.equals("0000")) {
						borrowOrderR.setLoanTime(fkDate);
						borrowOrderR.setStatus(BorrowOrder.STATUS_HKZ);
						Repayment repayment = new Repayment();
						repayment.setUserId(borrowOrderR.getUserId());
						repayment.setAssetOrderId(borrowOrderR.getId());
						repayment.setRepaymentAmount(Long.valueOf(borrowOrderR.getMoneyAmount()));
						repayment.setRepaymentedAmount(0L);
						repayment.setRepaymentPrincipal(Long.valueOf(borrowOrderR.getIntoMoney()));
						repayment.setRepaymentInterest(Long.valueOf(borrowOrderR.getLoanInterests()));
						repayment.setLateFeeApr(borrowOrderR.getLateFeeApr());
						repayment.setRepaymentTime(DateUtil.addDay(fkDate, borrowOrderR.getLoanTerm()));// 放款时间加上借款期限
						repayment.setCreatedAt(fkDate);
						repayment.setUpdatedAt(fkDate);
						repayment.setStatus(borrowOrderR.getStatus());
						repaymentService.insert(repayment);
						User user = userService.searchByUserid(borrowOrderR.getUserId());
						SendSmsUtil.sendSmsDiyCL(user.getUserPhone(), "你收到贷速侠打款" + borrowOrderR.getIntoMoney() / 100.00 + "元,预计很快到账，请注意查收！");

					} else {
						borrowOrderR.setUpdatedAt(fkDate);
						borrowOrderR.setStatus(BorrowOrder.STATUS_FKSB);
					}

				}
				borrowOrderService.updateById(borrowOrderR);
				SpringUtils.renderText(response, "true");
			} else {

				logger.error("放款回调，没有找到对应的借款信息：");
			}

		} catch (Exception e) {
			logger.error("放款回调失败，异常信息:", e);

		}*/

	}
/**
 * 提额记录表--用户借款管理--借款管理--user_limit_record
 * @param request
 * @param response
 * @param model
 * @return
 */
	@RequestMapping("getUserLimitPage")
	public String getUserLimitPage(HttpServletRequest request, HttpServletResponse response, Model model) {
		String url = "userInfo/userLimitRecordList";
		try {

			HashMap<String, Object> params = getParametersO(request);

			PageConfig<UserLimitRecord> pageConfig = borrowOrderService.finduserLimitPage(params);
			model.addAttribute("pm", pageConfig);

			model.addAttribute("params", params);// 用于搜索框保留值

		} catch (Exception e) {
			logger.error("getUserLimitPage error", e);
		}
		return url;
	}

	/**
	 * 导出放款Excel
	 */
	@RequestMapping("toFKExcel")
	public void toFKExcel(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> params = this.getParametersO(request);
		try {

			int size = 50000;
			params.put(Constant.PAGE_SIZE, size);
			params.put("statusList", Arrays.asList(BorrowOrder.STATUS_FSTG, BorrowOrder.STATUS_HKZ, BorrowOrder.STATUS_FKZ, BorrowOrder.STATUS_FKBH,
					BorrowOrder.STATUS_FKSB));
			int totalPageNum = borrowOrderService.findParamsCount(params);
			int total = 0;
			if (totalPageNum > 0) {
				if (totalPageNum % size > 0) {
					total = totalPageNum / size + 1;
				} else {
					total = totalPageNum / size;
				}
			}

			OutputStream os = response.getOutputStream();
			response.reset();// 清空输出流
			ExcelUtil.setFileDownloadHeader(request, response, "放款审核列表.xls");
			response.setContentType("application/msexcel");// 定义输出类型
			SXSSFWorkbook workbook = new SXSSFWorkbook(10000);

			String[] titles = { "序号", "订单号", "姓名", "手机号", "是否是老用户", "借款金额(元)", "天数", "服务费利率(万分之一)", "手续费", "到账金额", "下单时间", "放款时间", "子类型", "状态",
					"放款状态", "放款备注" };
			for (int i = 1; i <= total; i++) {
				params.put(Constant.CURRENT_PAGE, i);
				PageConfig<BorrowOrder> pm = borrowOrderService.findPage(params);
				List<BorrowOrder> borrowList = pm.getItems();
				List<Object[]> contents = new ArrayList<Object[]>();
				for (BorrowOrder borrowOrder : borrowList) {
					Object[] conList = new Object[titles.length];
					conList[0] = borrowOrder.getId();
					conList[1] = borrowOrder.getOutTradeNo();
					conList[2] = borrowOrder.getRealname();
					conList[3] = borrowOrder.getUserPhone();
					conList[4] = borrowOrder.getCustomerTypeName();
					conList[5] = new BigDecimal(borrowOrder.getMoneyAmount()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
					conList[6] = borrowOrder.getLoanTerm() + "天";
					conList[7] = new BigDecimal(borrowOrder.getApr()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
					conList[8] = new BigDecimal(borrowOrder.getLoanInterests()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
					conList[9] = new BigDecimal(borrowOrder.getIntoMoney()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
					conList[10] = borrowOrder.getOrderTime() == null ? "" : DateUtil.getDateFormat(borrowOrder.getOrderTime(),
							"yyyyyy-MM-dd HH:mm:ss");
					conList[11] = borrowOrder.getLoanTime() == null ? "" : DateUtil.getDateFormat(borrowOrder.getLoanTime(), "yyyyyy-MM-dd HH:mm:ss");
					conList[12] = borrowOrder.getOrderTypeName();
					conList[13] = borrowOrder.getStatusName();
					conList[14] = borrowOrder.getPaystatus();
					conList[15] = borrowOrder.getPayRemark()==null?"":borrowOrder.getPayRemark();
					contents.add(conList);
				}
				ExcelUtil.buildExcel(workbook, "放款列表", titles, contents, i, pm.getTotalPageNum(), os);
			}
		} catch (Exception e) {
			logger.error("导出excel失败", e);
		}

	}

	@RequestMapping("getBorrowFreeBPage")
	public String getBorrowFreeBPage(HttpServletRequest request, HttpServletResponse response, Model model) {
		String url = "borrow/borrowFeeList_company";
		try {

			HashMap<String, Object> params = getParametersO(request);

			PageConfig<BorrowOrderLoan> pageConfig = borrowOrderService.findBorrowFreeBPage(params);
			model.addAttribute("pm", pageConfig);
			// model.addAttribute("borrowStatusMap",
			// BorrowOrder.borrowStatusMap);
			model.addAttribute("allstatus", BorrowOrderLoan.allstatus);
			model.addAttribute("params", params);// 用于搜索框保留值

		} catch (Exception e) {
			logger.error("getBorrowFreeBPage error", e);
		}
		return url;
	}

	/**
	 * 公司服务费统计
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("getBorrowFreeBStatisPage")
	public String getBorrowFreeBStatisPage(HttpServletRequest request, HttpServletResponse response, Model model) {
		String url = "borrow/borrowFeeList_company_statis";
		try {

			HashMap<String, Object> params = getParametersO(request);
			params.put("status", BorrowOrderLoan.FKCG);

			Long sumLoanInterest = borrowOrderService.findloanInterestsSucSumB(params);
			model.addAttribute("sumLoanInterest", sumLoanInterest);
			PageConfig<BorrowOrderLoan> pageConfig = borrowOrderService.findBorrowFreeBStatisPage(params);
			model.addAttribute("pm", pageConfig);
			// model.addAttribute("borrowStatusMap",
			// BorrowOrder.borrowStatusMap);
			model.addAttribute("allstatus", BorrowOrderLoan.allstatus);
			model.addAttribute("params", params);// 用于搜索框保留值

		} catch (Exception e) {
			logger.error("getBorrowFreeBPage error", e);
		}
		return url;
	}

	/**
	 * 个人服务费统计
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("getBorrowFreeCStatisPage")
	public String getBorrowFreeCStatisPage(HttpServletRequest request, HttpServletResponse response, Model model) {
		String url = "borrow/borrowFeeList_person_statis";
		try {

			HashMap<String, Object> params = getParametersO(request);
			params.put("status", BorrowOrderLoan.FKCG);
			Long sumLoanInterest = borrowOrderService.findloanInterestsSucSumC(params);
			model.addAttribute("sumLoanInterest", sumLoanInterest);
			PageConfig<BorrowOrderLoanPerson> pageConfig = borrowOrderService.findBorrowFreeCStatisPage(params);
			model.addAttribute("pm", pageConfig);

			model.addAttribute("params", params);// 用于搜索框保留值

		} catch (Exception e) {
			logger.error("getBorrowFreeBPage error", e);
		}
		return url;
	}

	/**
	 * 服务费重新审核设置可重新放款
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @param borrowStatus
	 */
	@RequestMapping("againLoan/{loantype}")
	public void againLoan(HttpServletRequest request, HttpServletResponse response, Model model, @PathVariable("loantype") String loantype) {
		HashMap<String, Object> params = this.getParametersO(request);
		boolean flag = false;
		try {
			String yurref = params.get("yurref").toString();
			if (yurref != null) {
				flag = borrowOrderService.loanAgainFee(yurref, loantype);

			}

		} catch (Exception e) {
			logger.error("againLoan error", e);
		}
		SpringUtils.renderDwzResult(response, flag, flag ? "操作成功" : "该订单不能重新放款或者操作失败！请确认该订单信息", DwzResult.CALLBACK_CLOSECURRENTDIALOG,
				params.get("parentId").toString());
	}
	
	

	/**
	 * 用户批量重新放款
	 * 批量重新放款审核（按钮）--放款审核列表
	 * @param request
	 * @param response
	 * @param model
	 * @param borrowStatus
	 */
	@RequestMapping("againToBatchLoan")
	public void againToBatchLoan(HttpServletRequest request, HttpServletResponse response, Model model) {

		HashMap<String, Object> params = this.getParametersO(request);
		boolean flag = false;
		try {

			if (!params.containsKey("idsBorrow") || params.get("idsBorrow") == null) {

				SpringUtils.renderDwzResult(response, false, "权限问题，请使用正确的访问方式！", DwzResult.CALLBACK_CLOSECURRENTDIALOG, params.get("parentId")
						.toString());

			} else {
				BackUser backUser = loginAdminUser(request);
				backUserService.insertLog(new BackLog(loginAdminUser(request).getId(), "againToBatchLoan", params.get("idsBorrow").toString()));
				HashMap<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("ids", params.get("idsBorrow"));
				paramMap.put("statusList", Arrays.asList(BorrowOrder.STATUS_FKZ, BorrowOrder.STATUS_FKSB));

				List<BorrowOrder> list = borrowOrderService.findAll(paramMap);
				if (list != null && list.size() > 0) {
					int succCount = 0;
					int errorCount = 0;
					StringBuilder sbu=new StringBuilder();
					Date nowDate = new Date();
					List<BorrowOrder> jmsPojoList=new ArrayList<BorrowOrder>();
					for (BorrowOrder borrowOrderR : list) {
						Date  updateTime=borrowOrderR.getUpdatedAt();
						//当前时间大于更新时间且时间差小于半个 小时  
						boolean checkIsApproved =DateUtil.checkIsApproved(nowDate, updateTime);
						if(checkIsApproved){
							errorCount++;
							sbu.append(borrowOrderR.getOutTradeNo()).append(",");
							// 状态必须为放款中或者放款失败，而且......
						}else if ((borrowOrderR.getStatus().intValue() == BorrowOrder.STATUS_FKZ || borrowOrderR.getStatus().intValue() == BorrowOrder.STATUS_FKSB)
								&& borrowOrderR.getStatus().intValue() != BorrowOrder.STATUS_HKZ
								&& !borrowOrderR.getPaystatus().equals(BorrowOrder.SUB_PAY_CSZT)
								&& !borrowOrderR.getPaystatus().equals(BorrowOrder.SUB_PAY_SUCC)) {
							List<Repayment> lists = repaymentService.findAllByBorrowId(borrowOrderR.getId());
							if (lists == null || lists.size() < 1) {
 								succCount++;
								BorrowOrder borrowOrder = new BorrowOrder();
								borrowOrder.setId(borrowOrderR.getId());
								borrowOrder.setRemark("批量重新放款操作！" + borrowOrderR.getRemark()  + "，招行订单号："
										+ borrowOrderR.getYurref() + ",上次支付结果：" + borrowOrder.getPaystatus());
								borrowOrder.setYurref(GenerateNo.payRecordNo("A"));
								borrowOrder.setSerialNo(GenerateNo.generateShortUuid(10));
								borrowOrder.setPaystatus(BorrowOrder.SUB_PAY_CSZT);
								borrowOrder.setStatus(BorrowOrder.STATUS_FKZ);
								borrowOrder.setUpdatedAt(new Date());
								borrowOrder.setVerifyLoanTime(new Date());
								borrowOrder.setVerifyLoanUser(backUser.getUserAccount());
								borrowOrder.setVerifyLoanRemark("批量重新放款：" + borrowOrder.getRemark());
								borrowOrder.setUserId(borrowOrderR.getUserId());
								borrowOrderService.updateById(borrowOrder);
								jmsPojoList.add(borrowOrder);
							} else {
								errorCount++; 
								sbu.append(borrowOrderR.getOutTradeNo()).append(",");
							}
						} else {
							errorCount++;
							sbu.append(borrowOrderR.getOutTradeNo()).append(",");
						}

					}
					if(CollectionUtils.isNotEmpty(jmsPojoList)){
						try {
							tsOrdersService.sendBorrowStatusByBatch(jmsPojoList);
						} catch (Exception e) {
							logger.error("sendBorrowStatusByBatch:",e);
						}
					}
					
					SpringUtils.renderDwzResult(response, true, "成功" + succCount + "笔，失败" + errorCount + "笔，失败订单列表订单号" + sbu.toString()
							+ "不能被进行重新放款操作，如有疑问请联系技术人员！", DwzResult.CALLBACK_CLOSECURRENTDIALOG, params.get("parentId").toString());

				} else {

					SpringUtils.renderDwzResult(response, false, "无记录,或选中订单不支持重新放款，请确认！", DwzResult.CALLBACK_CLOSECURRENTDIALOG,
							params.get("parentId").toString());

				}
			}
		} catch (Exception e) {
			logger.error("againToBatchLoan error", e);
		}
		// SpringUtils.renderDwzResult(response, flag, flag ?
		// "操作成功，两次操作间隔不低于五分钟" : "操作失败！请确认该订单信息",
		// DwzResult.CALLBACK_CLOSECURRENTDIALOG,
		// params.get("parentId").toString());
	}

	/**
	 * 服务费重新放款(会执行放款操作)
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @param borrowStatus
	 */
	@RequestMapping("againToFeeLoan")
	public void againToFeeLoan(HttpServletRequest request, HttpServletResponse response, Model model) {
		HashMap<String, Object> params = this.getParametersO(request);
		boolean flag = false;
		String remark = "(公司+个人)";
		try {
			if (params.containsKey("loanType")) {
				String loanType = params.get("loanType").toString();
				if (loanType.equals("loanB") || loanType.equals("loanC")) {
					remark = loanType.equals("loanB") ? "(单独运行公司)" : "(单独运行个人)";
					if (loanType.equals("loanC")) {

						Thread t = new Thread(new Runnable() {
							@Override
							public void run() {
								int ii = 0;
								while (ii < 5) {
									taskJob.payLoanInterestPays("loanC");
									logger.error("person loanterest count==" + ii);
									ii++;
									try {
										Thread.sleep(1000 * 30);// 睡眠30秒

									} catch (InterruptedException e) {
									}
								}
								logger.error("person finish====");

							}
						});
						t.start();

					} else {
						taskJob.payLoanInterestPays(loanType);
					}

				} else {
					SpringUtils.renderDwzResult(response, flag, "参数错误,请检查参数！", DwzResult.CALLBACK_CLOSECURRENTDIALOG, params.get("parentId")
							.toString());
					return;
				}

			} else {
				taskJob.payLoanInterestPays(null);
			}

			flag = true;
		} catch (Exception e) {
			logger.error("againToFeeLoan error", e);
		}
		SpringUtils.renderDwzResult(response, flag, flag ? remark + "操作成功，稍后查询结果。两次操作间隔不低于五分钟" : remark + "操作失败！如要继续操作，请五分钟后再进行！",
				DwzResult.CALLBACK_CLOSECURRENTDIALOG, params.get("parentId").toString());
	}

	@RequestMapping("getBorrowFreeCPage")
	public String getBorrowFreeCPage(HttpServletRequest request, HttpServletResponse response, Model model) {
		String url = "borrow/borrowFeeList_person";
		try {

			HashMap<String, Object> params = getParametersO(request);

			PageConfig<BorrowOrderLoanPerson> pageConfig = borrowOrderService.findBorrowFreeCPage(params);
			model.addAttribute("pm", pageConfig);
			// model.addAttribute("borrowStatusMap",
			// BorrowOrder.borrowStatusMap);
			model.addAttribute("allstatus", BorrowOrderLoan.allstatus);
			model.addAttribute("params", params);// 用于搜索框保留值

		} catch (Exception e) {
			logger.error("getBorrowFreeCPage error", e);
		}
		return url;
	}

	/**
	 * 导出资产Excel(公司)
	 */
	@RequestMapping("toBorrowFreeBExcel")
	public void toBorrowFreeBExcel(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> params = this.getParametersO(request);
		try {
			int size = 50000;
			params.put(Constant.PAGE_SIZE, size);
			Integer totalPageNum = borrowOrderService.findBorrowFreeBCount(params);
			int total = 0;
			if (totalPageNum > 0) {
				if (totalPageNum % size > 0) {
					total = totalPageNum / size + 1;
				} else {
					total = totalPageNum / size;
				}
			}

			OutputStream os = response.getOutputStream();
			response.reset();// 清空输出流
			ExcelUtil.setFileDownloadHeader(request, response, "服务费统计.xls");
			response.setContentType("application/msexcel");// 定义输出类型
			SXSSFWorkbook workbook = new SXSSFWorkbook(10000);
			String[] titles = { "用户ID", "借款订单号", "招行订单号", "金额(元)", "创建时间", "状态", "放款状态", "放款备注", "更新时间", "放款时间" };
			for (int i = 1; i <= total; i++) {
				params.put(Constant.CURRENT_PAGE, i);
				PageConfig<BorrowOrderLoan> pm = borrowOrderService.findBorrowFreeBPage(params);

				List<BorrowOrderLoan> borrowList = pm.getItems();
				List<Object[]> contents = new ArrayList<Object[]>();
				for (BorrowOrderLoan borrowOrderLoan : borrowList) {
					Object[] conList = new Object[titles.length];
					conList[0] = borrowOrderLoan.getUserId();
					conList[1] = borrowOrderLoan.getAssetOrderId();
					conList[2] = borrowOrderLoan.getYurref();
					// if("0".equals(borrowOrder.getCustomerType())){
					// conList[3] = "新用户";
					// }else{
					// conList[3] = "老用户用户";
					// }

					conList[3] = new BigDecimal(borrowOrderLoan.getLoanInterests()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_UP);
					conList[4] = borrowOrderLoan.getCreatedAt() == null ? "" : DateUtil.getDateFormat(borrowOrderLoan.getCreatedAt(),
							"yyyy-MM-dd HH:mm:ss");
					conList[5] = borrowOrderLoan.getStatusShow();
					conList[6] = borrowOrderLoan.getPayStatus();
					conList[7] = borrowOrderLoan.getPayRemark();
					conList[8] = borrowOrderLoan.getUpdatedAt() == null ? "" : DateUtil.getDateFormat(borrowOrderLoan.getUpdatedAt(),
							"yyyy-MM-dd HH:mm:ss");
					conList[9] = borrowOrderLoan.getLoanTime() == null ? "" : DateUtil.getDateFormat(borrowOrderLoan.getLoanTime(),
							"yyyy-MM-dd HH:mm:ss");
					contents.add(conList);
				}
				ExcelUtil.buildExcel(workbook, "信息列表", titles, contents, i, pm.getTotalPageNum(), os);
			}
		} catch (Exception e) {
			logger.error("导出excel失败", e);
		}

	}

	/**
	 * 导出资产Excel(公司)统计
	 */
	@RequestMapping("toBorrowFreeBStatisExcel")
	public void toBorrowFreeBStatisExcel(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> params = this.getParametersO(request);
		params.put("status", BorrowOrderLoan.FKCG);
		try {
			int size = 50000;
			params.put(Constant.PAGE_SIZE, size);
			Integer totalPageNum = borrowOrderService.findBorrowFreeBStatisCount(params);
			int total = 0;
			if (totalPageNum > 0) {
				if (totalPageNum % size > 0) {
					total = totalPageNum / size + 1;
				} else {
					total = totalPageNum / size;
				}
			}

			String fileName = "服务费统计-公司";
			if (params.containsKey("beginTime")) {
				fileName += "(" + params.get("beginTime");
			}
			if (params.containsKey("endTime")) {
				fileName += "&" + params.get("endTime") + ")";
			}
			fileName += ".xls";
			OutputStream os = response.getOutputStream();
			response.reset();// 清空输出流
			ExcelUtil.setFileDownloadHeader(request, response, fileName);
			response.setContentType("application/msexcel");// 定义输出类型
			SXSSFWorkbook workbook = new SXSSFWorkbook(10000);
			String[] titles = { "招行订单号", "金额(元)", "创建时间", "状态", "放款状态", "放款备注", "更新时间", "放款时间" };
			for (int i = 1; i <= total; i++) {
				params.put(Constant.CURRENT_PAGE, i);
				PageConfig<BorrowOrderLoan> pm = borrowOrderService.findBorrowFreeBStatisPage(params);

				List<BorrowOrderLoan> borrowList = pm.getItems();
				List<Object[]> contents = new ArrayList<Object[]>();
				for (BorrowOrderLoan borrowOrderLoan : borrowList) {
					Object[] conList = new Object[titles.length];
					conList[0] = borrowOrderLoan.getYurref();

					conList[1] = new BigDecimal(borrowOrderLoan.getLoanInterests()).divide(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN);
					conList[2] = borrowOrderLoan.getCreatedAt() == null ? "" : DateUtil.getDateFormat(borrowOrderLoan.getCreatedAt(),
							"yyyy-MM-dd HH:mm:ss");
					conList[3] = borrowOrderLoan.getStatusShow();
					conList[4] = borrowOrderLoan.getPayStatus();
					conList[5] = borrowOrderLoan.getPayRemark();
					conList[6] = borrowOrderLoan.getUpdatedAt() == null ? "" : DateUtil.getDateFormat(borrowOrderLoan.getUpdatedAt(),
							"yyyy-MM-dd HH:mm:ss");
					conList[7] = borrowOrderLoan.getLoanTime() == null ? "" : DateUtil.getDateFormat(borrowOrderLoan.getLoanTime(),
							"yyyy-MM-dd HH:mm:ss");
					contents.add(conList);
				}
				ExcelUtil.buildExcel(workbook, "信息列表", titles, contents, i, pm.getTotalPageNum(), os);
			}
		} catch (Exception e) {
			logger.error(" toBorrowFreeBStatisExcel 导出excel失败", e);
		}

	}

	/**
	 * 导出资产Excel(个人)统计
	 */
	@RequestMapping("toBorrowFreeCStatisExcel")
	public void toBorrowFreeCStatisExcel(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> params = this.getParametersO(request);
		params.put("status", BorrowOrderLoan.FKCG);
		try {
			int size = 50000;
			params.put(Constant.PAGE_SIZE, size);
			Integer totalPageNum = borrowOrderService.findBorrowFreeCStatisCount(params);
			int total = 0;
			if (totalPageNum > 0) {
				if (totalPageNum % size > 0) {
					total = totalPageNum / size + 1;
				} else {
					total = totalPageNum / size;
				}
			}
			String fileName = "服务费统计-个人";
			if (params.containsKey("beginTime")) {
				fileName += "=(" + params.get("beginTime") + "&";
			}
			if (params.containsKey("endTime")) {
				fileName += params.get("endTime") + ")";
			}
			fileName += ".xls";
			OutputStream os = response.getOutputStream();
			response.reset();// 清空输出流
			ExcelUtil.setFileDownloadHeader(request, response, fileName);
			response.setContentType("application/msexcel");// 定义输出类型
			SXSSFWorkbook workbook = new SXSSFWorkbook(10000);
			String[] titles = { "招行订单号", "金额(元)", "创建时间", "状态", "放款状态", "放款备注", "更新时间", "放款时间" };
			for (int i = 1; i <= total; i++) {
				params.put(Constant.CURRENT_PAGE, i);
				PageConfig<BorrowOrderLoanPerson> pm = borrowOrderService.findBorrowFreeCStatisPage(params);

				List<BorrowOrderLoanPerson> borrowList = pm.getItems();
				List<Object[]> contents = new ArrayList<Object[]>();
				for (BorrowOrderLoanPerson borrowOrderLoan : borrowList) {
					Object[] conList = new Object[titles.length];

					conList[0] = borrowOrderLoan.getYurref();

					conList[1] = new BigDecimal(borrowOrderLoan.getLoanInterests()).divide(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN);
					conList[2] = borrowOrderLoan.getCreatedAt() == null ? "" : DateUtil.getDateFormat(borrowOrderLoan.getCreatedAt(),
							"yyyy-MM-dd HH:mm:ss");
					conList[3] = borrowOrderLoan.getStatusShow();
					conList[4] = borrowOrderLoan.getPayStatus();
					conList[5] = borrowOrderLoan.getPayRemark();
					conList[6] = borrowOrderLoan.getUpdatedAt() == null ? "" : DateUtil.getDateFormat(borrowOrderLoan.getUpdatedAt(),
							"yyyy-MM-dd HH:mm:ss");
					conList[7] = borrowOrderLoan.getLoanTime() == null ? "" : DateUtil.getDateFormat(borrowOrderLoan.getLoanTime(),
							"yyyy-MM-dd HH:mm:ss");
					contents.add(conList);
				}
				ExcelUtil.buildExcel(workbook, "信息列表", titles, contents, i, pm.getTotalPageNum(), os);
			}
		} catch (Exception e) {
			logger.error(" toBorrowFreeCStatisExcel 导出excel失败", e);
		}

	}

	/**
	 * 导出资产Excel(个人)
	 */
	@RequestMapping("toBorrowFreeCExcel")
	public void toBorrowFreeCExcel(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> params = this.getParametersO(request);
		try {
			int size = 50000;
			params.put(Constant.PAGE_SIZE, size);
			Integer totalPageNum = borrowOrderService.findBorrowFreeCCount(params);
			int total = 0;
			if (totalPageNum > 0) {
				if (totalPageNum % size > 0) {
					total = totalPageNum / size + 1;
				} else {
					total = totalPageNum / size;
				}
			}

			OutputStream os = response.getOutputStream();
			response.reset();// 清空输出流
			ExcelUtil.setFileDownloadHeader(request, response, "服务费统计.xls");
			response.setContentType("application/msexcel");// 定义输出类型
			SXSSFWorkbook workbook = new SXSSFWorkbook(10000);
			String[] titles = { "用户ID", "借款订单号", "招行订单号", "金额(元)", "创建时间", "状态", "放款状态", "放款备注", "更新时间", "放款时间" };
			for (int i = 1; i <= total; i++) {
				params.put(Constant.CURRENT_PAGE, i);
				PageConfig<BorrowOrderLoanPerson> pm = borrowOrderService.findBorrowFreeCPage(params);
				List<BorrowOrderLoanPerson> borrowList = pm.getItems();
				List<Object[]> contents = new ArrayList<Object[]>();
				for (BorrowOrderLoanPerson borrowOrderLoan : borrowList) {
					Object[] conList = new Object[titles.length];
					conList[0] = borrowOrderLoan.getUserId();
					conList[1] = borrowOrderLoan.getAssetOrderId();
					conList[2] = borrowOrderLoan.getYurref();
					// if("0".equals(borrowOrder.getCustomerType())){
					// conList[3] = "新用户";
					// }else{
					// conList[3] = "老用户用户";
					// }

					conList[3] = new BigDecimal(borrowOrderLoan.getLoanInterests()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_UP);
					conList[4] = borrowOrderLoan.getCreatedAt() == null ? "" : DateUtil.getDateFormat(borrowOrderLoan.getCreatedAt(),
							"yyyy-MM-dd HH:mm:ss");
					conList[5] = borrowOrderLoan.getStatusShow();
					conList[6] = borrowOrderLoan.getPayStatus();
					conList[7] = borrowOrderLoan.getPayRemark();
					conList[8] = borrowOrderLoan.getUpdatedAt() == null ? "" : DateUtil.getDateFormat(borrowOrderLoan.getUpdatedAt(),
							"yyyy-MM-dd HH:mm:ss");
					conList[9] = borrowOrderLoan.getLoanTime() == null ? "" : DateUtil.getDateFormat(borrowOrderLoan.getLoanTime(),
							"yyyy-MM-dd HH:mm:ss");
					contents.add(conList);
				}
				ExcelUtil.buildExcel(workbook, "信息列表", titles, contents, i, pm.getTotalPageNum(), os);
			}
		} catch (Exception e) {
			logger.error("导出excel失败", e);
		}

	}

	/**
	 * 导出对账Excel
	 */
	@RequestMapping("toDzExcel/{borrowStatus}")
	public void toDzExcel(HttpServletRequest request, HttpServletResponse response, @PathVariable("borrowStatus") String borrowStatus) {
		HashMap<String, Object> params = this.getParametersO(request);
		try {
			int size = 50000;
			int total = 0;
			params.put(Constant.PAGE_SIZE, size);
			params.put("statusList", Arrays.asList(BorrowOrder.STATUS_HKZ, BorrowOrder.STATUS_BFHK, BorrowOrder.STATUS_YHK, BorrowOrder.STATUS_YQYHK,
					BorrowOrder.STATUS_YHZ, BorrowOrder.STATUS_KKZ, BorrowOrder.STATUS_YYQ));
			// params.put("borrowStatus", borrowStatus);
			int totalPageNum = borrowOrderService.findParamsCount(params);
			if (totalPageNum > 0) {
				if (totalPageNum % size > 0) {
					total = totalPageNum / size + 1;
				} else {
					total = totalPageNum / size;
				}
			}
			OutputStream os = response.getOutputStream();
			response.reset();// 清空输出流
			ExcelUtil.setFileDownloadHeader(request, response, "订单对账统计.xls");
			response.setContentType("application/msexcel");// 定义输出类型
			SXSSFWorkbook workbook = new SXSSFWorkbook(10000);
			String[] titles = { "债权编号", "第三方订单号", "招行订单号", "手机号码", "借款人", "身份证号码", "借款金额", "实际到账金额", "还款期限", "放款时间", "状态" };
			for (int i = 1; i <= total; i++) {
				params.put(Constant.CURRENT_PAGE, i);
				PageConfig<BorrowOrder> pm = borrowOrderService.findPage(params);
				List<BorrowOrder> borrowList = pm.getItems();
				List<Object[]> contents = new ArrayList<Object[]>();
				for (BorrowOrder borrowOrder : borrowList) {
					Object[] conList = new Object[titles.length];
					conList[0] = borrowOrder.getId();
					conList[1] = borrowOrder.getOutTradeNo();
					conList[2] = borrowOrder.getYurref();
					conList[3] = borrowOrder.getUserPhone();
					conList[4] = borrowOrder.getRealname();
					conList[5] = borrowOrder.getIdNumber();
					conList[6] = new BigDecimal(borrowOrder.getMoneyAmount()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
					conList[7] = new BigDecimal(borrowOrder.getIntoMoney()).divide(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN);
					conList[8] = borrowOrder.getLoanTerm() + "天";
					conList[9] = borrowOrder.getLoanTime() == null ? "" : DateUtil.getDateFormat(borrowOrder.getLoanTime(), "yyyy-MM-dd HH:mm:ss");
					conList[10] = "放款成功";
					contents.add(conList);
				}
				ExcelUtil.buildExcel(workbook, "用户列表", titles, contents, i, pm.getTotalPageNum(), os);
			}
		} catch (Exception e) {
			logger.error("导出excel失败", e);
		}

	}
	/*
	 * 资产信息----数据分析-----borrow_order_checking
	 */
	@RequestMapping("getBorrowOrderCheckPage")
	public String getBorrowOrderCheckPage(HttpServletRequest request, HttpServletResponse response, Model model) {

		try {
			HashMap<String, Object> params = getParametersO(request);
			PageConfig<BorrowOrderChecking> pageConfig = borrowOrderService.findBorrowOrderCheckPage(params);
			model.addAttribute("pm", pageConfig);
			model.addAttribute("allstatus", BorrowOrderChecking.allstatus);
			model.addAttribute("capitalTypeMap", BorrowOrderChecking.capitalTypeMap);
			model.addAttribute("params", params);// 用于搜索框保留值
		} catch (Exception e) {
			logger.error("getBorrowOrderCheckPage error", e);
		}
		return "borrow/borrowOrderCheckPage";
	}
	
	/*
	 * 资产信息附表----数据分析---borrow_order_checking_ext
	 */
		@RequestMapping("getBorrowOrderCheckExtPage")
		public String getBorrowOrderCheckExtPage(HttpServletRequest request, HttpServletResponse response, Model model){
			try {
				HashMap<String, Object> params = getParametersO(request);
				PageConfig<BorrowOrderCheckingExt> pageConfig = borrowOrderService.findBorrowOrderCheckExtPage(params);
				model.addAttribute("pm", pageConfig);
				model.addAttribute("allstatus", BorrowOrderChecking.allstatus);
				model.addAttribute("capitalTypeMap", BorrowOrderCheckingExt.capitalZCMTypeMap);
				model.addAttribute("params", params);// 用于搜索框保留值
			} catch (Exception e) {
				logger.error("getBorrowOrderCheckPage error", e);
			}
			return "borrow/borrowOrderCheckExtPage";
		}
		
		/**
		 * TODO：于
		 * 导出招财猫 资产
		 */
		@RequestMapping("toBorrowChceckExtExcel")
		public void toExtBorrow(HttpServletRequest request, HttpServletResponse response){
			HashMap<String, Object> params = this.getParametersO(request);
			try {
				int size = 50000;
				params.put(Constant.PAGE_SIZE, size);
				int totalPageNum = borrowOrderService.findBorrowOrderCheckExtCount(params);
				int total = 0;
				if (totalPageNum > 0) {
					if (totalPageNum % size > 0) {
						total = totalPageNum / size + 1;
					} else {
						total = totalPageNum / size;
					}
				}
				OutputStream os = response.getOutputStream();
				response.reset();// 清空输出流
				ExcelUtil.setFileDownloadHeader(request, response, "资产信息附表统计.xls");
				response.setContentType("application/msexcel");// 定义输出类型
				SXSSFWorkbook workbook = new SXSSFWorkbook(10000);
				String[] titles = { "借款订单ID", "姓名", "手机号码", "身份证", "银行卡号", "是否老用户", "借款金额", "借款期限",  "实际到账金额", "放款时间", "资产所属","更新时间" };
				for (int i = 1; i <= total; i++) {
					params.put(Constant.CURRENT_PAGE, i);
					PageConfig<BorrowOrderCheckingExt> pm = borrowOrderService.findBorrowOrderCheckExtPage(params);
					List<BorrowOrderCheckingExt> borrowList = pm.getItems();
					List<Object[]> contents = new ArrayList<Object[]>();
					for (BorrowOrderCheckingExt borrowOrder : borrowList) {
						Object[] conList = new Object[titles.length];
						conList[0] = borrowOrder.getAssetOrderId();
						conList[1] = borrowOrder.getRealname();
						conList[2] = borrowOrder.getUserPhone();
						conList[3] = borrowOrder.getIdNumber();
						conList[4] = borrowOrder.getCardNo();
						// if("0".equals(borrowOrder.getCustomerType())){
						// conList[3] = "新用户";
						// }else{
						// conList[3] = "老用户用户";
						// }
						conList[5] = User.customerTypes.get(borrowOrder.getCustomerType() + "");
						conList[6] = new BigDecimal(borrowOrder.getMoneyAmount()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
						conList[7] = borrowOrder.getLoanTerm() + "天";
						conList[8] = new BigDecimal(borrowOrder.getIntoMoney()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
						conList[9] = DateUtil.getDateFormat(borrowOrder.getLoanTime(), "yyyy-MM-dd HH:mm:ss");
						//TODO：不确定的状态显示什么
						if(BorrowOrderCheckingExt.capitalZCMTypeMap.containsKey(borrowOrder.getCapitalType())){
							conList[10] = BorrowOrderCheckingExt.capitalZCMTypeMap.get(borrowOrder.getCapitalType());
						}else{
							conList[10] ="";
						}
						conList[11] = DateUtil.getDateFormat(borrowOrder.getUpdatedAt(), "yyyy-MM-dd HH:mm:ss");

						contents.add(conList);
					}
					ExcelUtil.buildExcel(workbook, "信息列表", titles, contents, i, pm.getTotalPageNum(), os);
				}
			} catch (Exception e) {
				logger.error("导出excel失败", e);
			}
		}
		
	
	

	/**
	 * 导出资产Excel
	 */
	@RequestMapping("toBorrowChceckExcel")
	public void toBorrowChceckExcel(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> params = this.getParametersO(request);
		try {
			int size = 50000;
			params.put(Constant.PAGE_SIZE, size);
			int totalPageNum = borrowOrderService.findBorrowOrderCheckCount(params);
			int total = 0;
			if (totalPageNum > 0) {
				if (totalPageNum % size > 0) {
					total = totalPageNum / size + 1;
				} else {
					total = totalPageNum / size;
				}
			}
			OutputStream os = response.getOutputStream();
			response.reset();// 清空输出流
			ExcelUtil.setFileDownloadHeader(request, response, "资产信息统计.xls");
			response.setContentType("application/msexcel");// 定义输出类型
			SXSSFWorkbook workbook = new SXSSFWorkbook(10000);
			String[] titles = { "借款订单ID", "姓名", "手机号码", "身份证", "银行卡号", "是否老用户", "借款金额", "借款期限",  "实际到账金额", "放款时间", "资产所属","更新时间" };
			for (int i = 1; i <= total; i++) {
				params.put(Constant.CURRENT_PAGE, i);
				PageConfig<BorrowOrderChecking> pm = borrowOrderService.findBorrowOrderCheckPage(params);
				List<BorrowOrderChecking> borrowList = pm.getItems();
				List<Object[]> contents = new ArrayList<Object[]>();
				for (BorrowOrderChecking borrowOrder : borrowList) {
					Object[] conList = new Object[titles.length];
					conList[0] = borrowOrder.getAssetOrderId();
					conList[1] = borrowOrder.getRealname();
					conList[2] = borrowOrder.getUserPhone();
					conList[3] = borrowOrder.getIdNumber();
					conList[4] = borrowOrder.getCardNo();
					// if("0".equals(borrowOrder.getCustomerType())){
					// conList[3] = "新用户";
					// }else{
					// conList[3] = "老用户用户";
					// }
					conList[5] = User.customerTypes.get(borrowOrder.getCustomerType() + "");
					conList[6] = new BigDecimal(borrowOrder.getMoneyAmount()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
					conList[7] = borrowOrder.getLoanTerm() + "天";
					conList[8] = new BigDecimal(borrowOrder.getIntoMoney()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
					conList[9] = DateUtil.getDateFormat(borrowOrder.getLoanTime(), "yyyy-MM-dd HH:mm:ss");
					conList[10] = BorrowOrderChecking.capitalTypeMap.get(borrowOrder.getCapitalType());
					conList[11] = DateUtil.getDateFormat(borrowOrder.getUpdatedAt(), "yyyy-MM-dd HH:mm:ss");

					contents.add(conList);
				}
				ExcelUtil.buildExcel(workbook, "信息列表", titles, contents, i, pm.getTotalPageNum(), os);
			}
		} catch (Exception e) {
			logger.error("导出excel失败", e);
		}

	}
	

	@RequestMapping("testxx")
	public void testxx(HttpServletRequest request, HttpServletResponse response, Model model) {

		try {
			taskJob.assetsDivision();
			// 查询状态
			// taskJob.queryPaysStateNotCmb();
			// taskJob.queryPaysStateCmb();
			// HttpRequestCMBHL.getRequestNTQRYEBPStr();
			// System.out.println("zz");
			// taskJob.updateLoanTerm();

		} catch (Exception e) {
			logger.error("getUserLimitPage error", e);
		}

	}
}
